//备注：拷贝代码请加上作者信息
//作者：王海涛
//邮箱：1126471088@qq.com
//版本：V1.0.0
/********************************************************
    说明：
    1、每个外挂的CAN模块自行配置CAN参数。
    2、MCU自动提供CAN实时状态。
    3、支持普通发数据、中断接收数据、中断发送数据。
    4、CAN1接口为PB8/PB9。CAN2的IO当前未支持。
    5、基于STM32F10X标准库V3.6.0
**********************************************************/

#ifndef __CAN_BSP_H__
#define __CAN_BSP_H__

/*****************************************************/
#include "stm32f10x.h"
#include "stm32f10x_can.h"
#include "misc.h"
#include "../GPIO_BSP/gpio_bsp.h"
#include "FreeRTOS.h"
#include "task.h"
/*****************************************************/


/*CAN号枚举*/
typedef enum
{
    CAN_1 = CAN1_BASE,//CAN1
    CAN_2 = CAN2_BASE,//CAN2
}WHT_CAN_enum;

/*CAN状态枚举*/
typedef enum
{
    CAN_TRx_Idle = 0,//空闲
    CAN_TRx_Busy = 1,//忙碌

    CAN_No_Error = 0,//无错误码
    CAN_Tx_Error = 2,//发送错误
}WHT_CAN_State_enum;

/* CAN错误 */
typedef struct
{
    unsigned int error_count;        // 总错误计数
    unsigned int error_ewg_count;    // 错误警告计数
    unsigned int error_epv_count;    // 错误被动计数
    unsigned int error_bof_count;    // 总线关闭计数
    unsigned int last_error_code;    // 最后错误代码
    unsigned int last_error_time;    // 最后错误时间戳
    unsigned char is_error_passive;  // 错误被动状态标志
    unsigned char is_bus_off;        // 总线关闭状态标志
}WHT_CAN_Error_State_t;

/*CAN信息结构体*/
typedef struct
{
    WHT_CAN_State_enum TRx_State;       //忙碌标志,自动清零
    WHT_CAN_State_enum TRx_Error_State; //错误标志,自动清零
    WHT_CAN_Error_State_t Error_State;  //自动更新,可手动清零
}WHT_CAN_Info_t;

/*CAN配置结构体*/
typedef struct
{
    unsigned char PreemptionPriority;//抢占优先级
    unsigned char SubPriority;       //子优先级
    void (*Tx_IT_Callback)(void);
    void (*Rx_IT_Callback)(unsigned int id, unsigned char* const buffer, unsigned char length);

    unsigned int ID;                 //CAN ID 高3Bit不要用
    unsigned short prescaler;        //16 => 250khz 8 => 500khz  4 => 1mhz
}WHT_CAN_Config_t;

typedef struct
{
    unsigned int ID;        //高3Bit不要用
    unsigned char length;
    unsigned char buffer[8];
    unsigned char state;
}WHT_CAN_Message_t;


/*CAN回调函数结构体*/
typedef struct
{
    WHT_CAN_Info_t* WHT_CAN1_Info;//状态信息
    WHT_CAN_Info_t* WHT_CAN2_Info;//状态信息
    ErrorStatus (*WHT_Config)(WHT_CAN_enum name, const WHT_CAN_Config_t* config);                           //配置
    ErrorStatus (*WHT_TxMessage)(WHT_CAN_enum name, WHT_CAN_Message_t* tx_message, unsigned int timeout_ms);//普通发送
    ErrorStatus (*WHT_TxMessage_IT)(WHT_CAN_enum name, WHT_CAN_Message_t* tx_message);                      //中断发送
    //默认中断接收已开启
}WHT_CAN_BSP_t;

/*全局常量*/
extern const WHT_CAN_BSP_t WHT_CAN_BSP;

#endif /*__CAN_BSP_H__*/
